package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.Shop;
import com.hmdp.entity.Voucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherMapper;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IVoucherService;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private VoucherOrderServiceImpl voucherOrderServiceImpl;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        //初始化Lua脚本对象
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }


    private class VoucherOrderHandler implements Runnable {

        String queueName = "stream.orders";

        @Override
        public void run() {
            while (true){

                try {
                    //1.获取消息队列中的订单信息 xreadgroup group g1 c1 count 1 block 2000 streams stream.orders
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            //消费者组key，消费者key
                            Consumer.from("g1", "c1"),
                            //一次读一个，读不到阻塞两秒
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            //队列名，读的是最近未消费的消息
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2.判断消息获取是否成功
                    if (list == null || list.isEmpty()) {
                        //2.1 如果获取失败，说明没有消息，继续下一次循环
//                        log.info("消息队列无消息... ...");
                        continue;
                    }

                    //3.如果获取成功，解析数据，可以下单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    handleVoucherOrder(voucherOrder);

                    //4.ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                    handlePendingList();
                }

            }
        }

        private void handlePendingList()  {
            while (true){

                try {
                    //1.获取pending-list中的订单信息 xreadgroup group g1 c1 count 1  streams stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            //消费者组key，消费者key
                            Consumer.from("g1", "c1"),
                            //一次读一个
                            StreamReadOptions.empty().count(1),
                            //队列名，读的是最近未消费的消息
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2.判断消息获取是否成功
                    if (list == null || list.isEmpty()) {
                        //2.1 如果获取失败，说明pending-list中没有异常消息消息，结束循环
                        break;
                    }

                    //3.如果获取成功，解析数据，可以下单
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);

                    handleVoucherOrder(voucherOrder);

                    //4.ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                } catch (Exception e) {
                    log.error("处理pending-list订单异常",e);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException ex) {
                        throw new RuntimeException(ex);
                    }
                }

            }
        }


    }
    private void handleVoucherOrder(VoucherOrder voucherOrder) {

        //5.扣减库存
        boolean b = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();

        //6.创建订单
        this.save(voucherOrder);
    }

    /**
     * 秒杀优惠券
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        long orderId = redisIdWorker.nextId("order");

        // 1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString(), String.valueOf(orderId)
        );
        int r = result.intValue();
        // 2.判断结果是否为0
        if (r != 0) {
            // 2.1.不为0 ，代表没有购买资格
            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
        }

//        SECKILL_ORDER_EXECUTOR.submit(() -> {
//        //5.扣减库存
//        boolean b = seckillVoucherService.update()
//                .setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .gt("stock", 0)
//                .update();
//
//        //6.创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //6.1 订单id
//        voucherOrder.setId(orderId);
//        //6.2 优惠券id
//        voucherOrder.setVoucherId(voucherId);
//        //6.3 用户id
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        this.save(voucherOrder);
//
//        });

        // 3.返回订单id
        return Result.ok(orderId);

    }


    /**
     * 秒杀优惠券
     * @param voucherId
     * @return
     */
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券信息
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        LocalDateTime beginTime = seckillVoucher.getBeginTime();
//        LocalDateTime endTime = seckillVoucher.getEndTime();
//
//        //2.判断优惠券是否有效
//        LocalDateTime now = LocalDateTime.now();
//        if(beginTime.isAfter(now) || endTime.isBefore(now)){
//            //2.1 无效时间直接返回提示
//            return Result.fail("请在有效时间内使用优惠券");
//        }
//
//        //3.判断库存是否充足
//        if(seckillVoucher.getStock() < 1){
//            //3.1 不足
//            return Result.fail("优惠券已经被抢完了");
//        }
//        //加锁确保每一个人只能抢到一张券
//        synchronized(UserHolder.getUser().getId().toString().intern()){
//            //这里注入本类调用方法是因为用this调用本类方法的话不走代理，事务会失效
//            return voucherOrderServiceImpl.refresh(voucherId);
//        }
//    }

    //更新库存和订单
//    @Transactional
//    public Result refresh(Long voucherId) {
//        //4.保证一个用户只能枪一张优惠券
//        Long count = this.query().
//                eq("voucher_id", voucherId).
//                eq("user_id", UserHolder.getUser().getId()).
//                count();
//        if(count >= 1){
//            return Result.fail("你已抢过该优惠券了");
//        }
//        //5.扣减库存
//        boolean b = seckillVoucherService.update()
//                .setSql("stock = stock - 1")
//                .eq("voucher_id", voucherId)
//                .gt("stock", 0)
//                .update();
//
//        if(!b){
//            return Result.fail("优惠券已经被抢完了");
//        }
//        //6.创建订单
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //6.1 订单id
//        long id = redisIdWorker.nextId("order");
//        voucherOrder.setId(id);
//        //6.2 优惠券id
//        voucherOrder.setVoucherId(voucherId);
//        //6.3 用户id
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//        this.save(voucherOrder);
//
//
//        return Result.ok(id);
//    }
}
